package com.beetobe.callib.event;

import java.io.IOException;
import java.util.Date;
import java.util.StringTokenizer;
import java.util.TimeZone;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.text.format.Time;
import android.util.Log;

import com.beetobe.callib.CalendarLibHelper;
import com.beetobe.callib.CalendarLibHelper.SelectDay;
import com.google.api.client.util.DateTime;
import com.google.api.services.calendar.model.Event;
import com.google.api.services.calendar.model.EventDateTime;
import com.google.api.services.calendar.model.Events;

public class AsyncEditEvent extends AsyncTask<Void, Void, Void> {
	private final ProgressDialog dialog;
	private com.google.api.services.calendar.Calendar client;
	private String calendarId;

	public AsyncEditEvent(Activity activity, String calendarId) {
		this.calendarId = calendarId;
		client = CalendarLibHelper.client;
		dialog = new ProgressDialog(activity);
	}

	protected void onPreExecute() {
		super.onPreExecute();
		dialog.setMessage("일정을 수정합니다...");
		dialog.show();

	}

	@Override
	protected Void doInBackground(Void... arg0) {
		// TODO Auto-generated method stub
		try {
			boolean is_exist;
			CalendarLibHelper.eventList.clear();
			com.google.api.services.calendar.model.Calendar calendar = client
					.calendars().get(calendarId).execute();
			Time now = new Time();
			now.setToNow();
			Events events = client.events().list(calendar.getId())
					.setTimeMin(getEventTime(-3)).setTimeMax(getEventTime(3))
					.execute();

			for (Event event : events.getItems()) {
				EventInfo info = new EventInfo(event.getId(),
						event.getSummary());

				StringTokenizer tokenizer = new StringTokenizer(
						info.toString(), "ㅫ");
				String date = tokenizer.nextToken();
				String content = tokenizer.nextToken();

				StringTokenizer dateToken = new StringTokenizer(date, ".");
				int year = Integer.parseInt(dateToken.nextToken());
				int month = Integer.parseInt(dateToken.nextToken());
				int day = Integer.parseInt(dateToken.nextToken());
				// selectDay에 없고 calendar에 있을 떄 삭제
				is_exist = true;
				for (int i = 0; i < CalendarLibHelper.selectDay.size(); i++) {

					if (content.equals("[GUEST]" + CalendarLibHelper.accountName)) {
						is_exist = false;
						if (CalendarLibHelper.selectDay.get(i).getDay() == day
								&& CalendarLibHelper.selectDay.get(i)
										.getMonth() == month
								&& CalendarLibHelper.selectDay.get(i).getYear() == year) {
							is_exist = true;
							break;
						}
					}

				}
				if (!is_exist) {
					client.events().delete(calendarId, info.getId()).execute();
				}

			}
			
			// selectDay에 있고 calendar에 없을 때 생성
			for (int i = 0; i < CalendarLibHelper.selectDay.size(); i++) {
				is_exist = false;
				for (Event event : events.getItems()) {
					EventInfo info = new EventInfo(event.getId(),
							event.getSummary());

					StringTokenizer tokenizer = new StringTokenizer(
							info.toString(), "ㅫ");
					String date = tokenizer.nextToken();
					String content = tokenizer.nextToken();
					
					if(!content.equals("[GUEST" + CalendarLibHelper.accountNick
							+ "]" + CalendarLibHelper.accountName))
					{
						continue;
					}
					
					StringTokenizer dateToken = new StringTokenizer(date, ".");
					int year = Integer.parseInt(dateToken.nextToken());
					int month = Integer.parseInt(dateToken.nextToken());
					int day = Integer.parseInt(dateToken.nextToken());

					if (CalendarLibHelper.selectDay.get(i).getDay() == day
							&& CalendarLibHelper.selectDay.get(i).getMonth() == month
							&& CalendarLibHelper.selectDay.get(i).getYear() == year) {
						is_exist = true;
					}
				}
				if (!is_exist) {

					Event event = new Event();
					SelectDay day = CalendarLibHelper.selectDay.get(i);

					event.setStart(new EventDateTime()
							.setDateTime(getStartEventTime(day.getYear(),
									day.getMonth() - 1, day.getDay() - 1)));
					event.setEnd(new EventDateTime()
							.setDateTime(getEndEventTime(day.getYear(),
									day.getMonth() - 1, day.getDay() - 1)));
					event.setSummary(day.getYear() + "." + day.getMonth() + "."
							+ day.getDay() + "ㅫ" + "[GUEST]"
							+ CalendarLibHelper.accountName);

					// 이벤트 생성
					Event createdEvent = client.events()
							.insert(calendarId, event).execute();

					EventInfo info = new EventInfo(createdEvent.getId(),
							createdEvent.getSummary());
					CalendarLibHelper.eventList.add(info);
				}
			}

		} catch (IOException e) {
			// CalendarActivity.handleGoogleException(e);
		} catch (NullPointerException e) {
			// 구현안됨 eventList가 빈 상태임
			// Toast.makeText(CalendarActivity.getApplicationContext(),
			// "이벤트가 존재하지 않습니다.", Toast.LENGTH_LONG).show();
		} finally {
			CalendarLibHelper.isEventInserted = true;
			// CalendarActivity.onRequestCompleted();
		}
		return null;
	}

	private DateTime getStartEventTime(int year, int month, int day) {
		Time makeTime = new Time();
		makeTime.set(-1, -1, 3, day + 1, month, year);
		// 월(month)은 그대로 넣어주고, 일(monthDay)은 +1해서 넣어줘야함
		makeTime.normalize(true);
		Date makeDate = new Date(makeTime.toMillis(false));
		DateTime makeDateTime = new DateTime(makeDate,
				TimeZone.getTimeZone("UTC"));
		return makeDateTime;
	}

	private DateTime getEndEventTime(int year, int month, int day) {
		Time makeTime = new Time();
		makeTime.set(-1, -1, 5, day + 1, month, year);
		// 월(month)은 그대로 넣어주고, 일(monthDay)은 +1해서 넣어줘야함
		makeTime.normalize(true);
		Date makeDate = new Date(makeTime.toMillis(false));
		DateTime makeDateTime = new DateTime(makeDate,
				TimeZone.getTimeZone("UTC"));
		return makeDateTime;
	}

	private DateTime getEventTime(int period) {
		Time endTime = new Time();
		endTime.setToNow();
		endTime.month += period;
		endTime.normalize(true);
		Date makeDate = new Date(endTime.toMillis(false));
		DateTime makeDateTime = new DateTime(makeDate,
				TimeZone.getTimeZone("UTC"));
		return makeDateTime;
	}

	protected void onPostExecute(Void result) {
		super.onPostExecute(result);

		dialog.dismiss();
	}

}
